import 'dart:async';
import 'package:flutter_reactive_ble/flutter_reactive_ble.dart';
import 'package:sleep/model/blue/blue_model.dart';
import 'package:sleep/model/blue_connect/blue_connect.dart';
import 'package:sleep/model/blue_connection_state.dart';

const Map<DeviceConnectionState, BlueConnectionState> stateMap = {
  DeviceConnectionState.connected: BlueConnectionState.connected,
  DeviceConnectionState.disconnected: BlueConnectionState.disconnected,
  DeviceConnectionState.connecting: BlueConnectionState.connectting,
  DeviceConnectionState.disconnecting: BlueConnectionState.disconnecting,
};

class BlueConnector {
  final FlutterReactiveBle ble;

  StreamSubscription? _connection;

  Stream<BlueConnectModel> get state => _deviceConnectionController.stream;
  final _deviceConnectionController = StreamController<BlueConnectModel>();

  BlueModel? blue;
  BlueConnector(this.ble) {
    listenBlueConnctState();
  }

  connect(BlueModel blue) {
    _connection = ble
        .connectToDevice(
            id: blue.deviceId, connectionTimeout: const Duration(seconds: 10))
        .listen((event) {});
  }

  listenBlueConnctState() {
    ble.connectedDeviceStream.listen((event) {
      _deviceConnectionController.add(BlueConnectModel(
        deviceId: event.deviceId,
        connectionState: stateMap[event.connectionState]!,
        failure: null,
      ));
    });
  }

  disconnect(BlueModel blue) {
    try {
      _connection?.cancel();
      _connection = null;
    } finally {
      _deviceConnectionController.add(BlueConnectModel(
        deviceId: blue.deviceId,
        connectionState: BlueConnectionState.disconnected,
        failure: null,
      ));
    }
  }

  Future<void> dispose() async {
    await _deviceConnectionController.close();
  }
}
